﻿using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

// [NetworkSettings(sendInterval = 0.05f)]
[RequireComponent(typeof (NetworkPosition), typeof (VelocitySimulate))]
public class SnakeBody : NetworkBehaviour {

    [SyncVar]
    public Transform prevBody;
    public float followSmooth;

    public float lifeTime = 2f;
    private float _lastActiveTime;

    private NetworkPosition _networkPosition;
    private VelocitySimulate _velocitySimulate;

    // Use this for initialization
    void Start() {
        // combine _networkPosition and _velocitySimulate
        _networkPosition = GetComponent<NetworkPosition>();
        _velocitySimulate = GetComponent<VelocitySimulate>();
        _velocitySimulate.SetPositionAction = v =>
        {
            _networkPosition.setPosition(v);
        };

        _lastActiveTime = Time.time;
    }

    // Update is called once per frame
    void Update() {
        // ** c/s both **
        if (prevBody != null) {
            _lastActiveTime = Time.time;
        }

        if (Time.time - _lastActiveTime > lifeTime) {
            Destroy(this.gameObject);
        }

        // if (isClient) {
        // }

        // ** server side **
        if (!isServer) return;
        if (prevBody != null) {
        // if (isClient && localPlayerAuthority && prevBody != null) {
            var dist = (prevBody.position - transform.position).magnitude;
            if (dist > 0.18f * 2) {
                // transform.position = Vector3.Lerp(transform.position, prevBody.position, followSmooth*Time.deltaTime*50f);
                var p = Vector3.Lerp(transform.position, prevBody.position, followSmooth*Time.deltaTime*60f);
                _velocitySimulate.addVelocityFromPosition(p);
//                GetComponent<NetworkPosition>().setPosition(p);
            }
        }
    }

}
